package com.cloudwise.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudwise.entity.ReturnBean;
import com.cloudwise.entity.Role;
import com.cloudwise.entity.RoleMenu;
import com.cloudwise.entity.UserRole;
import com.cloudwise.service.MenuService;
import com.cloudwise.service.RoleMenuService;
import com.cloudwise.service.RoleService;
import com.cloudwise.service.UserRoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("role")
public class RoleController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;
    @Resource
    private RoleMenuService roleMenuService;
    @Resource
    private UserRoleService userRoleService;

    /**
     * 分页查询所有数据
     *
     * @param role
     * @return 所有数据
     */
    @GetMapping
    public ReturnBean selectAll(Integer limit, Integer page, Role role) {
        Page<Role> rolePage = new Page<>(page, limit);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(role.getRoleName())) {
            queryWrapper.like("role_name", role.getRoleName());
        }
        if (ObjectUtil.isNotEmpty(role.getRoleKey())) {
            queryWrapper.like("role_key", role.getRoleKey());
        }
        Page<Role> page1 = this.roleService.page(rolePage, queryWrapper);
        return super.success(page1.getRecords(), page1.getTotal());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectRole")
    public ReturnBean selectOne(String id) {
        Role role = this.roleService.getById(id);
        return super.success(role, 1L);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ReturnBean delete(@RequestParam("idList[]") List<Long> idList) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id", idList);
        userRoleService.remove(queryWrapper);
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.in("role_id", idList);
        roleMenuService.remove(roleMenuQueryWrapper);
        boolean b = roleService.removeByIds(idList);
        if (b) {
            return super.success(idList);
        } else {
            return super.fail(idList);
        }
    }

    /**
     * 新增数据
     *
     * @param role 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    public ReturnBean insert(Role role, @RequestParam("menuIds[]") List<Integer> menuIds) {
        role.setCreateTime(new Date());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", role.getRoleName());
        Role one = roleService.getOne(queryWrapper);
        if (!ObjectUtil.isEmpty(one)) {
            return fail(null, "角色名不能重复");
        }
        boolean save;
        save = roleService.save(role);
        List<RoleMenu> roleMenuList = getRoleMenuListByMenuIds(role.getId(), menuIds);
        boolean saveBatch = roleMenuService.saveBatch(roleMenuList);
        if (save && saveBatch) {
            return success(role, 1L);
        } else {
            return fail(role);
        }
    }

    /**
     * 修改数据
     *
     * @param role
     * @return 修改结果
     */
    @PutMapping("/update")
    public ReturnBean update(Role role, @RequestParam("menuIds[]") List<Integer> menuIds) {
        role.setUpdateTime(new Date());
        boolean updateById = roleService.updateById(role);
        if(role.getStatus()==1){
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("role_id",role.getId());
            userRoleService.remove(userRoleQueryWrapper);
        }
        //查询role现在所拥有的menuId
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", role.getId());
        List<RoleMenu> list = roleMenuService.list(queryWrapper);
        if (list.size() > 0) {
            //保存了此role对应的所有menuId
            List<Integer> allMenuId = new LinkedList<>();
            for (RoleMenu roleMenu : list) {
                allMenuId.add(roleMenu.getMenuId());
            }
            //需要删除的menuIds
            List<Integer> delRoleIds = new LinkedList<>();
            for (Integer integer : allMenuId) {
                if (!menuIds.contains(integer)) {
                    delRoleIds.add(integer);
                }
            }
            if (delRoleIds != null && delRoleIds.size() > 0) {
                QueryWrapper<RoleMenu> delQuery = new QueryWrapper<>();
                delQuery.eq("role_id", role.getId());
                delQuery.in("menu_id", delRoleIds);
                roleMenuService.remove(delQuery);
            }
            List<Integer> addMenuIds = new LinkedList<>();
            for (Integer integer : menuIds) {
                if (!allMenuId.contains(integer)) {
                    addMenuIds.add(integer);
                }
            }
            if (allMenuId != null && allMenuId.size() > 0) {
                List<RoleMenu> addRoleMenus = new LinkedList<>();
                for (Integer addMenuId : addMenuIds) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setRoleId(role.getId());
                    roleMenu.setMenuId(addMenuId);
                    addRoleMenus.add(roleMenu);
                }
                roleMenuService.saveBatch(addRoleMenus);
            }
        }else {
            for (Integer menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(role.getId());
                roleMenuService.save(roleMenu);
            }
        }
        if (updateById) {
            return super.success(role, 1L);
        } else {
            return super.fail(role);
        }
    }

    @RequestMapping("/getCount")
    public ReturnBean getCount() {
        int count = this.roleService.count();
        return success(null, (long) count);
    }

    @GetMapping("findAllMenu")
    public ReturnBean findAllMenu() {
        List<Tree<String>> layuiTree = menuService.getLayuiTree();
        return super.success(layuiTree);

    }

    public List<RoleMenu> getRoleMenuListByMenuIds(Integer roleId, List<Integer> menuIds) {
        List<RoleMenu> roleMenuList = new ArrayList<>();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuList.add(roleMenu);
        }
        return roleMenuList;
    }

    @RequestMapping("/getAllRoleNoPage")
    public ReturnBean getAllRoleNoPage() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("status",1);
        List<Role> list = roleService.list(queryWrapper);
        return super.success(list, (long) list.size());
    }
}
